<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" @row-dblclick="getDrawer" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="sn" label="编号" width="320" sortable>
			</el-table-column>
			<el-table-column prop="name" label="名称" width="320" sortable>
			</el-table-column>
			<el-table-column label="操作" >
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next"
						   @current-change="handleCurrentChange"
						   :page-size="pageSize"
						   :total="total"
						   :current-page="currentPage"
						   style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增和编辑界面-->
		<el-dialog :title="title" :visible.sync="departmentFormVisible" :close-on-click-modal="false">
			<el-form :model="departmentForm" label-width="80px" :rules="departmentFormRules" ref="departmentForm">
				<el-form-item label="编号" prop="sn">
					<el-input v-model="departmentForm.sn" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="名称" prop="name">
					<el-input v-model="departmentForm.name" auto-complete="off"></el-input>
				</el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="departmentFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="departmentSubmit" :loading="departmentLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--抽屉-->
		<el-drawer
				title="明细查询"
				:visible.sync="drawer"
				direction="rtl"
				size="50%">

				<!--工具条-->
				<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
					<el-form :inline="true" :model="filters">
						<el-form-item>
							<el-button type="primary" @click="handleAdd1">新增</el-button>
						</el-form-item>
					</el-form>
				</el-col>
				<!--列表-->
				<el-table :data="departments1" highlight-current-row v-loading="listLoading1" @selection-change="selsChange" style="width: 100%;">
					<el-table-column type="selection" width="55">
					</el-table-column>
					<el-table-column type="index" width="60">
					</el-table-column>
					<el-table-column prop="name" label="明细名" width="100" sortable>
					</el-table-column>
					<el-table-column prop="type.name" label="产品类型" width="120" sortable>
					</el-table-column>

					<el-table-column label="操作" >
						<template scope="scope">
							<el-button size="small" @click="handleEdit1(scope.$index, scope.row)">编辑</el-button>
							<el-button type="danger" size="small" @click="handleDel1(scope.$index, scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			<!--新增和编辑界面-->
		</el-drawer>
		<!--新增和编辑界面-->
		<el-dialog :title="title" :visible.sync="departmentFormVisible1" :close-on-click-modal="false">
			<el-form :model="departmentForm1" label-width="80px" :rules="departmentFormRules" ref="departmentForm1">
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="departmentForm1.name" auto-complete="off"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="departmentFormVisible1 = false">取消</el-button>
				<el-button type="primary" @click.native="departmentSubmit1" :loading="departmentLoading1">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
    import util from '../../common/js/util'
    //import NProgress from 'nprogress'
    import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, departmentDepartment, addDepartment } from '../../api/api';

    export default {
        data() {
            return {
                drawer: false,
                dialog: false,
                loading: false,
                gridData: [],
                title:'',
				type:null,
                filters: {
                    keyword: ''//关键字
                },
                departments: [],
                departments1: [],
                employees:[],
                dictypeTree:[],
                total: 0,
                currentPage:1,
                pageSize: 5,
                listLoading: false,
                listLoading1: false,
                sels: [],//列表选中列

                departmentFormVisible: false,//编辑界面是否显示
                departmentFormVisible1: false,
                departmentLoading: false,
                departmentLoading1: false,
                departmentFormRules: {
                    name: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ]
                },
                //编辑界面数据
                departmentForm: {
                    id: null,
                    name: '',
                    sn: '',
                    state: 0,
                    manager: null,
                    parent: null,
                    dirPath:null
                },departmentForm1: {
                    id: null,
                    name: '',
                    type: null
                }
            }
        },
        methods: {
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {});
            },
            //抽屉获取明显
            getDrawer(row){
                this.type=row
                this.drawer = true;
                let id = row.id;
                this.$http.get("/dic/"+id)
					.then(result=>{
					    result=result.data;
						this.departments1=result;
					})
            },
            //显示新增界面
            handleAdd1: function () {
                this.title="新增";
                this.departmentFormVisible1 = true;
                this.departmentForm1 = {
                    id:null,
                    name: '',
                    type:null
                };
            },
            //编辑
            departmentSubmit1: function () {
                this.$refs.departmentForm1.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.departmentLoading1 = true;
                            let para = Object.assign({}, this.departmentForm1);
                            para.type=this.type
                            this.$http.put("/dic",para)
                                .then(result=>{//后端执行完成了
                                    this.departmentLoading1 = false;
                                    this.departmentFormVisible1 = false;//关闭列表加载忙等
                                    result = result.data;//  AjaxResult
                                    //{success:true,message:操作成功}
                                    //{success:false,message:操作失败}
                                    //1.提示
                                    if(result.success){
                                        this.$message({
                                            message: '操作成功！',
                                            type: 'success'
                                        });
                                    }else{
                                        this.$message({
                                            message: result.message,//提示后端的业务错误
                                            type: 'error'
                                        });
                                    }
                                    this.getDrawer(this.type)
                                })
                                .catch(result=>{
                                    this.departmentLoading1 = false;
                                    this.$message({
                                        message: '业务繁忙，稍后重试！',
                                        type: 'error'
                                    });
                                });
                        });
                    }
                });
            },
            search(){
                this.currentPage = 1;//定位到第一页
                this.getDepartments();
            },
            //性别显示转换
            /*formatSex: function (row, column) {
                return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
            },*/
            handleCurrentChange(val) {
                this.currentPage = val;
                this.getDepartments();
            },
            //获取用户列表
            getDepartments() {
                //DepartmentQuery
                let para = {
                    currentPage: this.currentPage,
                    pageSize:this.pageSize,
                    keyword: this.filters.keyword
                };
                this.listLoading = true;//开启忙等框
                //使用axios发送请求，从pethome拿数据 http://localhost:8080/dictype/list
                this.$http.post("/dictype/list",para)
                    .then(result=>{
                        this.listLoading = false;//关闭忙等框
                        console.log(result);
                        result = result.data;
                        this.departments = result.rows;
                        this.total=result.total;

                    })
                    .catch(result=>{
                        console.log(result);
                        this.$message({
                            message: '系统繁忙，稍后重试！！！',
                            type: 'error'
                        });
                    })
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    this.$http.delete("/dictype/"+row.id)
                        .then(result=>{//后端执行完成了
                            this.listLoading = false;//关闭盲等框
                            result = result.data;//返回的是AjaxResult
                            //{success:true,message:操作成功}
                            //{success:false,message:操作失败}
                            //1.提示
                            if(result.success){
                                this.$message({
                                    message: '操作成功',
                                    type: 'success'
                                });
                            }else {
                                this.$message({
                                    message: '系统繁忙，稍后重试！！！',
                                    type: 'error'
                                });
                            }
                            //刷新页面，是否需要定位到第一页
                            this.currentPage=1;
                            this.getDepartments();

                        })
                        .catch(result=>{
                            this.listLoading = false;//关闭盲等框
                            this.$message({
                                message: '系统繁忙，稍后重试！！！',
                                type: 'error'
                            });
                            this.currentPage=1;
                            this.getDepartments();
                        })
                }).catch(() => {

                });
            },//删除
            handleDel1: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading1 = true;
                    this.$http.delete("/dic/"+row.id)
                        .then(result=>{//后端执行完成了
                            this.listLoading1 = false;//关闭盲等框
                            result = result.data;//返回的是AjaxResult
                            //{success:true,message:操作成功}
                            //{success:false,message:操作失败}
                            //1.提示
                            if(result.success){
                                this.$message({
                                    message: '操作成功',
                                    type: 'success'
                                });
                            }else {
                                this.$message({
                                    message: '系统繁忙，稍后重试！！！',
                                    type: 'error'
                                });
                            }
                            //刷新页面，是否需要定位到第一页
                            this.getDrawer(this.type)
                        })
                        .catch(result=>{
                            this.listLoading1 = false;//关闭盲等框
                            this.$message({
                                message: '系统繁忙，稍后重试！！！',
                                type: 'error'
                            });
                        })
                }).catch(() => {

                });
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.getDeptTree();//触发加载部门树
                this.title="编辑";
                this.departmentFormVisible = true;
                //Object.assign({}, row) ：将当前数据克隆一份
                this.departmentForm = Object.assign({}, row);//做数据回显的
                let dirPath = row.dirPath;
                if (dirPath){ //列如：/51/52/53
                    dirPath = dirPath.split("/");//["","51","52","53"]
                    let parent = [];
                    for (let i=1;i<dirPath.length-1;i++){
                        parent.push(parseInt(dirPath[i]));
                    }//[51,52]
                    console.log(parent);
                    this.departmentForm.parent = parent;
                }

            },handleEdit1: function (index, row) {
                this.getDeptTree();//触发加载部门树
                this.title="编辑";
                this.departmentFormVisible1 = true;
                //Object.assign({}, row) ：将当前数据克隆一份
                this.departmentForm1 = Object.assign({}, row);//做数据回显的
            },
            //显示新增界面
            handleAdd: function () {
                this.getDeptTree();//触发加载部门树
                this.title="新增";
                this.departmentFormVisible = true;
                this.departmentForm = {
                    id: null,
                    name: '',
                    sn: '',
                    state: 0,
                    manager: null,
                    parent: null,
                    dirPath:null
                };
            },
            //编辑
            departmentSubmit: function () {
                this.$refs.departmentForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.departmentLoading = true;
                            let para = Object.assign({}, this.departmentForm);

                            //处理后端需要的数据格式
                            let parent = para.parent;//传的格式：[1,12],但是要的格式是{"id":12}
                            if(parent){//只要不为空的时候，才做操作
                                para.parent = {"id":parent[parent.length-1]}//拿到数组最后一个元素（需要的格式）
                            }

                            this.$http.put("/dictype",para)
                                .then(result=>{//后端执行完成了
                                    this.departmentLoading = false;
                                    this.departmentFormVisible = false;//关闭列表加载忙等
                                    result = result.data;//  AjaxResult
                                    //{success:true,message:操作成功}
                                    //{success:false,message:操作失败}
                                    //1.提示
                                    if(result.success){
                                        this.$message({
                                            message: '操作成功！',
                                            type: 'success'
                                        });
                                    }else{
                                        this.$message({
                                            message: result.message,//提示后端的业务错误
                                            type: 'error'
                                        });
                                    }
                                    //2.刷新页面  是否需要定位到第一
                                    this.currentPage = 1;
                                    this.departmentFormVisible = false;
                                    this.getDepartments();
                                })
                                .catch(result=>{
                                    this.departmentLoading = false;
                                    this.$message({
                                        message: '业务繁忙，稍后重试！',
                                        type: 'error'
                                    });
                                });

                            /*                            departmentDepartment(para).then((res) => {
                                                            this.departmentLoading = false;
                                                            //NProgress.done();
                                                            this.$message({
                                                                message: '提交成功',
                                                                type: 'success'
                                                            });
                                                            this.$refs['departmentForm'].resetFields();
                                                            this.departmentFormVisible = false;
                                                            this.getDepartments();
                                                        });*/
                        });
                    }
                });
            },
            selsChange: function (sels) {
                this.sels = sels;
            },
            //批量删除
            batchRemove: function () {
                var ids = this.sels.map(item => item.id);
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    this.$http.patch("/dictype",ids)
                        .then(result=>{//后端执行完成了
                            this.listLoading = false;//关闭列表加载忙等
                            result = result.data;//  AjaxResult
                            //{success:true,message:操作成功}
                            //{success:false,message:操作失败}
                            //1.提示
                            if(result.success){
                                this.$message({
                                    message: '操作成功！',
                                    type: 'success'
                                });
                            }else{
                                this.$message({
                                    message: result.message,//提示后端的业务错误
                                    type: 'error'
                                });
                            }
                            //2.刷新页面  是否需要定位到第一
                            this.currentPage = 1;
                            this.getDepartments();
                        })
                        .catch(result=>{
                            this.listLoading = false;//关闭列表加载忙等
                            console.log(result);
                            //1.提示
                            this.$message({
                                message: '系统繁忙，稍后重试！！！',
                                type: 'error'
                            });
                            //2.刷新页面 要   是否需要定位到第一页
                            this.currentPage = 1;
                            this.getDepartments();
                        });
                }).catch(() => {

                });
            },
            getEmployees(){
                this.$http.get("/employee")
                    .then(result=>{
                        result = result.data;// List<Employee>
                        this.employees = result;
                    })
            },
            getDeptTree(){
                this.$http.get("dictype/tree")
                    .then(result=>{
                        result=result.data;
                        this.dictypeTree=result;
                        console.log("dictypeTree+++++++");
                        console.log(this.dictypeTree);
                    })
            }
        },
        mounted() {
            //页面加载完毕，调用pethome拿出数据
            this.getDepartments();
            this.getEmployees();
        }
    }

</script>

<style scoped>

</style>